package com.jluzh.server;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author EvanHuang
 * @date 11/5/2018 2:12 PM
 * @since
 */
@Path("file")
public class UploadDownloadResource {

    /*//获取文件名；
        System.out.println("getFileName : " + disposition.getFileName());
    //获取字段名称，即<input type="file" name="xxx"）中的xxx
        System.out.println("getName : " + disposition.getName());
    //获取该段content-disposition的内容长度
        System.out.println("getSize : " + disposition.getSize());
    //获取该段content-disposition的类型，比如form-data
        System.out.println("getType : " + disposition.getType());
    //获取本次请求的请求值，比如{name=file, filename=3.jpg}
        System.out.println("getParameters : " + disposition.getParameters());*/
    @POST
    @Path("image1")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String upload(@FormDataParam("file") InputStream fileInputStream,
                         @FormDataParam("file") FormDataContentDisposition disposition, @Context ServletContext ctx) {

        File upload = new File(ctx.getRealPath("/upload"),
                UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(disposition.getFileName()));
        try {
            FileUtils.copyInputStreamToFile(fileInputStream, upload);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    @POST
    @Path("image2")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String upload2(@FormDataParam("file") FormDataBodyPart bp, @Context ServletContext ctx) {
        File upload = new File(ctx.getRealPath("/upload"), UUID.randomUUID().toString() + "."
                + FilenameUtils.getExtension(bp.getFormDataContentDisposition().getFileName()));
        try {
            FileUtils.copyInputStreamToFile(bp.getValueAs(InputStream.class), upload);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    @GET
    @Path("/images/{name}")
    public void showImg(@PathParam("name") String imageName, @Context HttpServletResponse response,
                        @Context ServletContext ctx) throws IOException {
        response.setHeader("Content-disposition", "attachment;filename="+imageName);
        response.setHeader("Cache-Control", "no-cache");
        File f = new File(ctx.getRealPath("/upload"), imageName);
        FileUtils.copyFile(f, response.getOutputStream());
    }

    @GET
    @Path("/images2/{name}")
    public Response showImg(@PathParam("name") String imageName, @Context ServletContext ctx) throws IOException {
        File f = new File(ctx.getRealPath("/upload"), imageName);
        if (!f.exists()) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } else {
            return Response.ok(f).header("Content-disposition", "attachment;filename=" + imageName)
                    .header("Cache-Control", "no-cache").build();
        }
    }

    @GET
    @Path("/images3/{name}")
    public Response showImg2(@PathParam("name") String imageName, @Context ServletContext ctx) throws IOException {
        final File f = new File(ctx.getRealPath("/upload"), imageName);
        if (!f.exists()) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } else {
            return Response.ok(new StreamingOutput() {
                @Override
                public void write(OutputStream output) throws IOException, WebApplicationException {
                    output.write(FileUtils.readFileToByteArray(f));
                }
            }).header("Content-disposition", "attachment;filename=" + imageName)
                    .header("Cache-Control", "no-cache").build();
        }
    }


}
